<template>
  <div>
    <a-modal
      :visible="visible"
      :title="''"
      :bodyStyle="{
        padding: '10px 20px',
      }"
      width="1000px"
      @cancel="cancelClick"
      destroyOnClose
      :zIndex="1000"
    >
      <template #footer>
        <a-row>
          <div
            style="display: flex; align-items: center; margin-bottom: 20px"
            v-if="material_type != 'text' && jobCategory != 'videoSplit'"
          >
            <div>素材名称：</div>
            <a-input
              v-model:value="autoName"
              placeholder="请输入素材名称"
              allowClear
              style="width: 895px"
            />
          </div>
          <a-col style="width: 100%; text-align: right">
            <a-space>
              <a-button @click="cancelClick" style="border-radius: 5px"
                >取消</a-button
              >
              <a-button
                v-if="aisave == false"
                style="border-radius: 5px"
                type="primary"
                :loading="loading"
                @click="submitClick"
                >确认</a-button
              >
              <a-button
                v-if="aisave == true"
                style="border-radius: 5px"
                type="primary"
                :loading="loading"
                @click="saveFn"
                >确认</a-button
              >
            </a-space>
          </a-col>
        </a-row>
      </template>
      <!-- <a-tab-pane v-show="isFlaking"  v-for="item in tabedList" :key="item.key" :tab="item.tab" /> -->

      <a-tabs v-model:activeKey="activeKey" @change="activeKeyChange">
        <a-tab-pane v-for="item in tabList" :key="item.key" :tab="item.tab" />
      </a-tabs>
      <a-row v-if="activeKey == 1">
        <div style="display: flex; max-height: 600px; overflow: auto">
          <a-col
            :span="8"
            style="padding: 0 20px; border-right: 1px solid #efeff5"
          >
            <div
              style="
                display: flex;
                height: 100%;
                flex-direction: column;
                justify-content: space-between;
              "
            >
              <div style="flex: 1">
                <div v-if="treeData.length">
                  <a-input-search
                    v-model:value="seatchValue"
                    placeholder="请输入项目名称搜索"
                    @search="onSearch"
                  />
                  <a-divider style="margin: 15px 0" />
                </div>
                <a-spin tip="加载中..." :spinning="spinning">
                  <a-menu
                    v-if="treeData.length"
                    v-model:openKeys="openKeys"
                    v-model:selectedKeys="selectedKeys"
                    mode="inline"
                    @click="handleClick"
                  >
                    <a-menu-item
                      v-for="(item, index) in treeData"
                      :key="item.id"
                    >
                      {{ item.name }}
                    </a-menu-item>
                  </a-menu>
                  <div v-else>
                    <a-empty :image="simpleImage" />
                  </div>
                </a-spin>
              </div>
              <!-- 只有当没有数据的时候才显示 -->
              <a-button
                v-if="!(Array.isArray(treeData) && treeData.length)"
                size="mini"
                style="width: 100%; margin-top: auto; font-size: 13px"
                @click="businessVisible = true"
              >
                <PlusOutlined />新增项目库
              </a-button>
            </div>
          </a-col>
          <a-col :span="16" class="right-content hide-scroller-bar">
            <a-spin tip="加载中..." :spinning="spinningFile">
              <a-row :gutter="[16, 1]" v-if="folderList.length" :wrap="true">
                <!-- 新建文件夹 -->
                <a-col>
                  <div
                    class="auto-file"
                    v-if="!showMaterial"
                    style="position: relative"
                  >
                    <div
                      style="
                        transform: scale(0.9);
                        position: absolute;
                        top: -6px;
                        left: 4px;
                      "
                    >
                      <folderList
                       :noupload="true"
                        @newFolder="newSubFolder"
                        :isLoading="folderLoading"
                        :list="folderData"
                        @choose="chooseFolder"
                      />
                    </div>
                  </div>
                </a-col>
                <a-col
                  v-for="item in folderList"
                  :key="item.id"
                  @click="folderClick(item)"
                >
                  <div
                    class="auto-file"
                    :class="folderId == item.id ? 'auto-border' : ''"
                  >
                    <div>
                      <cu-icon
                        class="icon"
                        type="icon-wenjianjia1"
                        style="font-size: 60px"
                      />
                    </div>
                    <div class="folder_namess">{{ item.folder_name }}</div>
                    <a-badge
                      v-if="
                        item?.statck_multimedias_count ||
                        item?.statck_texts_count
                      "
                      :count="
                        item?.statck_multimedias_count ||
                        item?.statck_texts_count
                      "
                      class="badge1"
                      style="background: rgba(0, 0, 0, 0.2)"
                    ></a-badge>
                    <div class="icon-contont">
                      <cu-icon
                        v-if="item?.folder_type == 'audio'"
                        class="icon-postion"
                        type="icon-yuyin"
                        style="font-size: 24px"
                      />
                      <cu-icon
                        v-if="item?.folder_type == 'image'"
                        class="icon-postion"
                        type="icon-tupian1"
                        style="font-size: 24px"
                      />
                      <cu-icon
                        v-if="item?.folder_type == 'video'"
                        class="icon-postion"
                        type="icon-shipin"
                        style="font-size: 24px"
                      />
                    </div>
                  </div>
                </a-col>
              </a-row>
              <a-empty v-else :image="simpleImage" />
            </a-spin>
          </a-col>
        </div>
      </a-row>
      <a-row v-else>
        <a-row
          :gutter="[16, 16]"
          v-if="folderList.length"
          class="content hide-scroller-bar"
        >
          <a-col v-for="item in folderList" :key="item.id">
            <div
              @click="folderClick(item)"
              class="auto-file"
              :class="folderId == item.id ? 'auto-border' : ''"
            >
              <div>
                <cu-icon
                  class="icon"
                  type="icon-wenjianjia1"
                  style="font-size: 60px"
                />
              </div>
              <div>{{ item.folder_name }}</div>
              <a-badge
                v-if="
                  item?.statck_multimedias_count || item?.statck_texts_count
                "
                :count="
                  item?.statck_multimedias_count || item?.statck_texts_count
                "
                class="badge1"
                style="background: rgba(0, 0, 0, 0.2)"
              ></a-badge>
              <div class="icon-contont">
                <cu-icon
                  v-if="item?.folder_type == 'audio'"
                  class="icon-postion"
                  type="icon-yuyin"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'image'"
                  class="icon-postion"
                  type="icon-tupian1"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'text'"
                  class="icon-postion"
                  type="icon-zhinengwenan"
                  style="font-size: 24px"
                />
                <cu-icon
                  v-if="item?.folder_type == 'video'"
                  class="icon-postion"
                  type="icon-shipin"
                  style="font-size: 24px"
                />
              </div>
            </div>
          </a-col>
        </a-row>
        <a-col :span="24" v-else style="text-align: center">
          <a-empty :image="simpleImage" />
        </a-col>
      </a-row>
    </a-modal>

    <!-- 新建文件夹 -->
    <NewFolder
      :isFlaking="isFlaking"
      :visible="addVisible"
      :is_merchant_library="1"
      @onCancel="addVisible = false"
      @onSubmit="closeAdd"
      :current_name="current_name"
      :defaultData="{
        type: '视频',
        isDisable: true,
      }"
      :groupData="{
        id: selectedKeys[0],
        default_group_id: currentLibrary?.groupid,
        merchant_library_id: currentLibrary?.merchant_library_id,
        group_name: currentLibrary?.group_name,
      }"
    />
  </div>

  <!-- 新增项目库 -->
  <NewMerchant
    :visible="businessVisible"
    @onCancel="businessVisible = false"
    @onSubmit="closeBUsinessModal"
  />
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import NewFolder from "@/views/shotstack/MaterialCenter/modules/NewFolder.vue";
import folderList from "@/views/shotstack/EditingCenter/modules/bottomSet/components/folderList.vue";
import { Form, message, Empty } from "ant-design-vue";
import request from "../../../../common/utils/request";
import { defineEmits } from "vue";
// 新增项目库按钮
import NewMerchant from "@/views/shotstack/MaterialCenter/modules/NewMerchant.vue";
import { PlusOutlined } from "@ant-design/icons-vue";

export default defineComponent({
  name: "materialsModule",
  components: {
    NewFolder,
    folderList,
    PlusOutlined,
    NewMerchant,
  },
  props: {
    // aisave : {
    //   type: Boolean,
    //   default: false,
    // },
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    material_type: {
      type: String,
      default: "audio",
    },
    jobCategory: {
      type: String,
      default: "",
    },
    tabHidden: {
      default: -1,
      type: Number,
    },
    // true 会emit('selfRequest'), false 不触发
    requestType: {
      type: Boolean,
      default: false,
    },
    aisave: {
      type: Boolean,
      default: false,
    },
    isFlaking: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      count: 0,
      activeKey: 1,
      seatchValue: "",
      treeData: [],
      fieldNames: {
        children: "folder_group",
        title: "name",
        key: "id",
      },
      MemberName: "",
      Checked_groupid: "",
      default_group_id: "",
      beforeDash: "",
      selectedKeys: [],
      expandedKeys: [],
      openKeys: [],
      spinning: false,
      spinningFile: false,
      folderList: [],
      folderId: 0,
      groupId: 0,
      autoName: "",
      merchant_library_id: "",
      loading: false,
      // 控制新增文件夹显示隐藏
      addVisible: false,
      // 当前素材库
      currentLibrary: {
        groupid: "",
        merchant_library_id: "",
        group_name: "",
      },
      // 文件夹加载
      folderLoading: false,
      // 文件夹数据
      folderData: [],
      // 当前文件夹
      currentFolder: {},
      tabList: [
        { key: 1, tab: "项目素材" },
        { key: 2, tab: "通用素材" },
      ],
      // 新增项目库
      businessVisible: false,
      current_name: "",
    });

    // 根据已选择的项, 获取当前选择的文件夹
    const saveTitle = computed(() => {
      const parent = state.treeData.find(
        (ele) => ele.id == state.Checked_groupid
      );
      const find = parent?.folder_group.find(
        (i) => i.id == state.selectedKeys?.[0]
      );
      let text = parent?.name || "";
      return text == "/" ? "--" : text;
    });

    // 关闭前的回调
    const closeAdd = (data) => {
      state.addVisible = false;
      state.selectedKeys[0] = data.merchant_library_id;
      state.openKeys[0] = data.merchant_library_id;
      getfolderList(data.merchant_library_id, data.group_id);
    };

    const closeBUsinessModal = () => {
      state.businessVisible = false;
      getWithGroupList();
    };

    // 新建文件夹
    const newSubFolder = () => {
      state.treeData.forEach((item) => {
        if (item.id == state.selectedKeys[0]) {
          state.currentLibrary.groupid = item.default_group_id;
          state.currentLibrary.merchant_library_id = item.id;
          state.currentLibrary.group_name = item.name;
        }
      });
      state.current_name = "null";
      state.addVisible = true;
    };

    // 选择文件夹
    const chooseFolder = (item) => {
      state.currentFolder = item;
      if (item.folder_type == "text") {
        getTextList({ merchant_folder_statck_id: item.id });
      } else {
        getMediaList({ merchant_folder_statck_id: item.id });
      }
      state.showMaterial = true;
    };

    const onSearch = () => {
      getWithGroupList();
    };

    const getWithGroupList = () => {
      let params = {
        name: state.seatchValue || undefined,
      };
      state.spinning = true;
      request
        .get("/work_ai", "/user/shotstack/library/withGroup/list")
        .then((res) => {
          if (res.result.length) {
            // 这里应该为成片库的
            res.result.forEach((item) => {
              item.folder_group.forEach((folder, index) => {
                folder.id = `${folder.id}-${index}`; //子级id处理 解决数组id一样导致的报错
                folder.name = folder.group_name;
              });
            });

            state.openKeys = [res.result[0].id];
            state.selectedKeys = [res.result[0].id];
            state.treeData = res.result.map((item) => {
              return {
                ...item,
                selectable: false,
              };
            });

            state.treeData = state.treeData.map((item) => ({
              ...item,
              folder_group: item.folder_group.map((groupItem) => ({
                ...groupItem,
                groupid: groupItem.id.split("-")[0],
              })),
            }));
            state.Checked_groupid = res.result[0].id;
          } else {
            state.treeData = [];
            state.folderList = [];
          }
          getfolderList(res.result[0].id, res.result[0].default_group_id);
          state.spinning = false;
        })
        .catch(() => {
          state.spinning = false;
        });
    };

    const getfolderList = (merchant_library_id, group_id) => {
      let params = {
        folder_use_type: 1,
        material_type: props.material_type,
        merchant_library_id,
        group_id,
        page:1,
        pageSize: 999999
      };
      if (props.isFlaking == true) {
        params.folder_use_type = 2;
      }
      state.spinningFile = true;
      request
        .post("/work_ai", "/user/shotstack/folder/list", params)
        .then((res) => {
          state.folderList = res.result.data;
          state.spinningFile = false;
        })
        .catch(() => {
          state.spinningFile = false;
        });
    };

    const selectChange = (key, e) => {
      // debugger
      console.log(state.treeData, "树");
      // state.Checked_groupid = e.node.id.split('-')[0]
      state.Checked_groupid = e.node.merchant_library_id;
      state.folderId = 0;
      getfolderList(e.node.merchant_library_id, e.node.id.split("-")[0]);
      console.log(state, "数据");
    };

    // 选中单个文件夹
    const folderClick = (data) => {
      // 这里能拿到所有id
      state.folderId = data.id;
      state.merchant_library_id = data.id;
      // state.merchant_library_id = data.merchant_library_id;
      state.groupId = data.group_id;
      state.MemberName = data.folder_name;
    };

    const activeKeyChange = (key) => {
      state.folderId = 0;
      state.folderList = [];
      if (key == 1) {
        getWithGroupList();
      } else {
        getfolderList(0, 0);
      }
    };

    const cancelClick = () => {
      emit("onCancel");
      state.MemberName = "";
    };

    // const emit = defineEmits(['updateData', 'callParentMethod']);

    // 智能拆分保存
    const saveFn = () => {
      if (state.MemberName.length == 0) {
        message.warn("请选择文件夹");
      } else {
        emit("saveMethod", state.merchant_library_id);
        emit("saveName", state.MemberName, state.merchant_library_id);
        state.MemberName = "";
      }
    };

    const submitClick = () => {
      if (!state.folderId) {
        message.warn("请选择要保存到的目录");
        return;
      }
      if (
        !state.autoName &&
        props.material_type != "text" &&
        props.jobCategory != "videoSplit"
      ) {
        message.warn("请输入素材名称");
        return;
      }

      let params = {
        material_type: props.material_type,
        merchant_folder_statck_id: state.folderId,
        group_id: state.groupId,
        material_name: state.autoName,
        material_url: props.data.material_url,
        merchant_library_id: state.selectedKeys,
        material_size: 0,
        down: 1,
        memberName: state.MemberName
      };

      // debugger
      if (props.requestType) {
        emit("selfRequest", params);
        state.loading = true;
        return;
      }

      if (props.material_type != "text") {
        state.loading = true;
        request
          .post("/work_ai", "/user/shotstack/media", params)
          .then((res) => {
            state.loading = false;
            message.success("保存成功");
            emit("onSuccess");
          })
          .catch(() => {
            state.loading = false;
          });
      } else {
        let params = {
          material_type: props.material_type,
          merchant_folder_statck_id: state.folderId,
          group_id: state.groupId,
          headline: [props?.data?.material_content],
        };
        state.loading = true;

        console.log(params, "params");
        request
          .post("/work_ai", "/user/shotstack/text", params)
          .then((res) => {
            state.loading = false;
            message.success("保存成功");
            emit("onSuccess");
          })
          .catch(() => {
            state.loading = false;
          });
      }
    };

    watch(
      () => props.isFlaking,
      (val) => {
        state.tabList = [];
        if (props.isFlaking == true) {
          state.tabList.push({ key: 1, tab: "项目成片" });
        } else {
          state.tabList.push(
            { key: 1, tab: "项目素材" },
            { key: 2, tab: "通用素材" }
          );
        }
      },
      { immediate: true }
    );

    // 获取列表展示数据
    const getWithGroupListFn = () => {
      state.autoName = props.data.autoName || "";
      if (props.tabHidden > 0) {
        let hiddenTabIndex = state.tabList.findIndex(
          (item) => item.key == props.tabHidden
        );
        hiddenTabIndex != -1 && state.tabList.splice(hiddenTabIndex, 1);
        state.activeKey = state.tabList[0].key;
        activeKeyChange(state.activeKey);
        return;
      }
      getWithGroupList();
    };
    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getWithGroupListFn();
        } else {
          state.folderId = 0;
          state.autoName = "";
        }
      }
    );

    // 关闭loading
    const stopLoding = () => {
      state.loading = false;
    };

    const handleClick = (menuInfo) => {
      let merchant_library_id;
      let group_id;
      state.treeData.forEach((item) => {
        if (item.id == menuInfo.key) {
          merchant_library_id = item.id;
          group_id = item.default_group_id;

          state.Checked_groupid = item.id;
        }
      });

      getfolderList(merchant_library_id, group_id);
    };
    return {
      ...toRefs(state),
      getWithGroupListFn,
      handleClick,
      cancelClick,
      onSearch,
      selectChange,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      saveTitle,
      folderClick,
      submitClick,
      saveFn,
      activeKeyChange,
      chooseFolder,
      stopLoding,
      newSubFolder,
      closeAdd,
      closeBUsinessModal,
    };
  },
});
</script>

<style lang="less" scoped>
.auto-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  border-radius: 5px;
  border: 2px solid #ffffff;
  cursor: pointer;
  position: reactive;

  .folder_namess {
    width: 120px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .icon-contont {
    position: absolute;
    top: 44px;
    left: 58px;
  }

  &:hover {
    background: #f2f2f2;
  }

  .badge1 {
    position: absolute;
    top: 21px;
    right: 32px;
    border-radius: 50%;
    color: #fff;
  }

  .badge2 {
    position: absolute;
    top: 13px;
    right: -40px;
    border-radius: 50%;
    color: #fff;
  }

  &.auto-border {
    border: 2px solid #3261fb;
  }
}

.right-content {
  padding: 0 20px;
  height: 370px;
  overflow: auto;
}

.content {
  height: 370px;
  overflow: auto;
}

:deep(.ss-menu-item-selected) {
  background-color: #c7e1fe !important;
}
</style>
